const {ipcMain} = require("electron");
const utf8 = require("utf8");

const pty = require('node-pty');
const os = require('os');
const userhome = require('user-home');

// 根据不同环境使用不同的shell类型
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';

function init(win) {
  console.log("target terminal")

  var ptyProcess = pty.spawn(shell, [], {
    name: 'xterm-color',
    cols: 80,
    rows: 30,
    cwd: process.env.HOME,
    env: process.env
  });

  // 绑定onData事件，通过ipc的onTerminal事件，把shell日志传到前端
  ptyProcess.onData((data) => {
    console.log("local terminal data:", data.toString('utf-8'));
    win.webContents.send("onTerminal", '', data.toString('utf-8'));
  });

  // socket绑定input事件，用于接收前端发送的命令，并传到ptyProcess中
  ipcMain.on("localStdin", function (event, data) {
    let obj = JSON.parse(data)
    if (obj.Op === "resize") {
      //console.log("client set cols, rows: ", obj.Cols, obj.Rows);
      ptyProcess.resize(obj.Rows, obj.Cols);
    } else if (obj.Op === "stdin") {
      //console.log("stdin: ", obj.Data);
      ptyProcess.write(obj.Data);
    }
  });

  ipcMain.on("localResize", function (event, size) {
      ptyProcess.resize(size[0], size[1]);
  });

  ipcMain.on("exit", function (event, size) {
      ptyProcess.destroy();
  });

  ipcMain.on("pid", function (event, size) {
      ptyProcess.pid;
  });
}

module.exports = init;
